package com.itboye.ihomebank.activity.me;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.ToggleButton;

import com.itboye.ihomebank.KeyFragment;
import com.itboye.ihomebank.R;
import com.itboye.ihomebank.activity.keytwo.KeyGuanLiActivity;
import com.itboye.ihomebank.activity.keytwo.KeyPuTongActivity;
import com.itboye.ihomebank.activity.keytwo.KeyZuHuActivity;
import com.itboye.ihomebank.activity.login.LoginActivity;
import com.itboye.ihomebank.base.BaseOtherActivity;
import com.itboye.ihomebank.base.MyApplcation;
import com.itboye.ihomebank.bean.ResultEntity;
import com.itboye.ihomebank.bean.UpdateVersionBean;
import com.itboye.ihomebank.constants.NetPublicConstant;
import com.itboye.ihomebank.constants.SPContants;
import com.itboye.ihomebank.db.DBOpenHelper;
import com.itboye.ihomebank.db.RecordDBManager;
import com.itboye.ihomebank.presenter.UpdatePresenter;
import com.itboye.ihomebank.ttKey.DbService;
import com.itboye.ihomebank.util.ByAlert;
import com.itboye.ihomebank.util.SPUtils;
import com.itboye.ihomebank.util.SaveKeyBean;
import com.itboye.ihomebank.util.UpdateManager;
import com.itboye.ihomebank.util.controller.LoginController;
import com.itboye.ihomebank.util.controller.UnLoginState;
import com.itboye.ihomebank.web.WebActivity;
import com.umeng.message.UTrack.ICallBack;

import java.util.Observable;
import java.util.Observer;

/**
 * 设置
 */
public class ActivitySetting extends BaseOtherActivity implements
        OnClickListener, Observer {
    View v_statusbar;
    ImageView close_icon;
    TextView add_shap_title_tv;
    ToggleButton toggle_button;// 切换按钮
    RelativeLayout seting_feed;// 反馈
    RelativeLayout seting_move;// 关于
    RelativeLayout seting_persondata;//个人资料
    TextView seting_ok;// 退出
    public static String EXITCHANGE = "com.itboye.ihomebank.person.exit";
    RecordDBManager dbManager;
    DBOpenHelper dbOpenHelper;
    String uid;

    UpdatePresenter updatePresenter;
    RelativeLayout seting_banben;
    TextView seting_new, seting_banbenhao;//提示new 版本号
    String versionNow;
    UpdateVersionBean appUpdateBean;
    String baima_mac;//绑定的白马mac地址(如果存在代表虽然绑定了锁，但是没有上传到我们的服务器)
    @Override
    public void onClick(View v) {
        Intent intent = null;
        switch (v.getId()) {
            case R.id.close_icon:
                finish();
                break;
            case R.id.seting_feed:// 反馈
                uid = SPUtils.get(this, null, SPContants.USER_ID, "") + "";
                if (uid.equals("")) {
                    intent = new Intent(this, LoginActivity.class);
                    startActivity(intent);
                } else {
                    intent = new Intent(this, ActivityFanKui.class);
                    startActivity(intent);
                }

                break;
            case R.id.seting_move:// 关于
                intent = new Intent(this, WebActivity.class);
                intent.putExtra("url", NetPublicConstant.WEB_URL
                        + "/about");
                intent.putExtra("title", "关于我们");
                startActivity(intent);
                break;
            case R.id.seting_ok:// 退出
                if (!baima_mac.equals("")) {
                    ByAlert.alert("数据不同步，请将锁数据上传之后，再退出");
                    return;
                }
                exit();
                break;
            case R.id.seting_banben:// 版本更新
//                onManager(appUpdateBean);
                if (seting_new.getVisibility() == View.VISIBLE) {
                    onManager(appUpdateBean);
                } else {
                    ByAlert.alert("已是最新版本");
                }
                break;
            case R.id.seting_persondata:
                LoginController.onMyPersonalCenter(this, null);
                break;
            default:
                break;
        }

    }

    public void exit() {
        // SPUtils.clear(ActivitySetting.this, "share_by_data");
        LoginController.setLoginState(new UnLoginState());
        // SPUtils.clear(MyApplcation.ctx, SPUtils.DEFAULT_FILE_NAME);
        deleteInfo();
        dbOpenHelper.deleteDatabase(this);
        try {
            KeyFragment.getInstance().panduan(null);
            KeyFragment.getInstance().refresh();
            DbService.deleteAllKey();

            if (KeyFragment.keyDao != null) {
                KeyFragment.keyDao.deleteAll();
            }
            if (KeyGuanLiActivity.keyDao != null) {
                KeyGuanLiActivity.keyDao.deleteAll();
            }
            if (KeyZuHuActivity.keyDao != null) {
                KeyZuHuActivity.keyDao.deleteAll();
            }
            if (KeyPuTongActivity.keyDao != null) {
                KeyPuTongActivity.keyDao.deleteAll();
            }
        } catch (Exception e) {
            // TODO: handle exception
        }

        Intent intent1 = new Intent(ActivityMyData.AVARTACTION);// 通知MeFragment更新界面
        sendBroadcast(intent1);
        ActivitySetting.this.finish();

    }

    @Override
    protected int layout_id() {
        // TODO Auto-generated method stub
        return R.layout.activity_setting;
    }

    @Override
    protected void onInitController() {
        // TODO Auto-generated method stub

    }

    private void deleteInfo() {
        dbManager = new RecordDBManager(this);
        dbManager.deleteCaoGao();
        MyApplcation.getInstance().mPushAgent.removeAlias(
                SPUtils.get(this, null, SPContants.USER_ID, "") + "", SPContants.UMENG_ALIAS,
                new ICallBack() {

                    @Override
                    public void onMessage(boolean arg0, String arg1) {
                        // TODO Auto-generated method stub

                    }
                });
        SPUtils.put(this, null, SPContants.USER_ID, "");
        SPUtils.put(this, null, SPContants.MOBILE, "");
        SPUtils.put(this, null, SPContants.EMAIL, "");
        SPUtils.put(this, null, SPContants.NICK, "");
        SPUtils.put(this, null, SPContants.PASSWORD, "");
        SPUtils.put(this, null, SPContants.AVATAR_URL, "");
        SPUtils.put(this, null, SPContants.USERNAME, "");
        SPUtils.put(this, null, SPContants.WX_Openid, "");
        SPUtils.put(this, null, SPContants.IdentityValidate, "");
        SPUtils.put(this, null, SPContants.BrokerValidate, "");
        SPUtils.put(this, null, SPContants.IS_LOGINED, false);
        SPUtils.put(this, null, SPContants.IdNumBer, "");
        SPUtils.put(this, null, SPContants.RealName, "");
        SPUtils.put(this, null, SPContants.WalletPass, "");
        SPUtils.put(this, null, SPContants.HUANKUAN, "");
        SPUtils.put(this, null, SPContants.OPENID, "");
        SaveKeyBean.saveData("2", null);
        SaveKeyBean.saveDataTwo("2", null);
        SPUtils.put(this, null, SPContants.RECORDS, "");
        SPUtils.put(this, null, SPContants.RECORDS_LOCKID, "");

        SPUtils.put(this, null, SPContants.MESS_NEW, false);
        SPUtils.put(this, null, SPContants.BAIMA_LOCKMAC, "");
        SPUtils.put(this, null, SPContants.BAIMA_DATE, "");
        SPUtils.put(this, null, SPContants.CHANGYONG_MAC, "");
        SPUtils.put(this, null, SPContants.CHANGYONG_TYPE, "");
        SPUtils.put(this, null, SPContants.KEY_PLAY, "");
        //红点
        SPUtils.put(ActivitySetting.this,null,SPContants.YUQI_COUNT,0);//逾期合同数
        SPUtils.put(ActivitySetting.this,null,SPContants.TOTAL_MESSAGE,0);//消息总数
        SPUtils.put(ActivitySetting.this,null,SPContants.SYSTEM_MESSAGE,0);//系统消息

        SPUtils.put(ActivitySetting.this,null,SPContants.CONTRANCT_MESSAGE,0);//签约消息
        SPUtils.put(ActivitySetting.this,null,SPContants.LOCK_MESSAGE,0);//锁消息
        SPUtils.put(ActivitySetting.this,null,SPContants.REPAIR_COUNT,0);//未维修数
        SPUtils.put(ActivitySetting.this,null,SPContants.BILL_COUNT,0);//账单数
        SPUtils.put(ActivitySetting.this,null,SPContants.FUJIAN_ORDER,false);//有无未填写的附件单
    }

    @Override
    protected void onInit() {
        // TODO Auto-generated method stub
        setStatusBarHeight(v_statusbar);
        add_shap_title_tv.setText("设置");
        baima_mac = (String) SPUtils.get(MyApplcation.ctx, null, SPContants.BAIMA_LOCKMAC, "");
        dbOpenHelper = new DBOpenHelper(this);

        versionNow = getAppVersionName(this);
        seting_banbenhao.setText("当前版本:" + versionNow);
        updatePresenter = new UpdatePresenter(this);
        UpdateVersionBean updateVersionBean = new UpdateVersionBean();
        updatePresenter.Update(updateVersionBean);
    }

    @Override
    protected void onReadIntent(Bundle bundle) {
        // TODO Auto-generated method stub

    }

    @Override
    public void update(Observable observable, Object data) {
        ResultEntity entity = handlerError(data);
        if (entity != null) {
            if (entity.getEventType() == UpdatePresenter.update_success) {
                appUpdateBean = (UpdateVersionBean) entity.getData();
                Log.d("====log==",appUpdateBean.toString());
                //seting_banbenhao.setText(appUpdateBean.getVersion());
                if (versionNow.equals(appUpdateBean.getVersion() + "")) {
                    seting_new.setVisibility(View.GONE);
                } else {
                    seting_new.setVisibility(View.VISIBLE);

                }
            } else if (entity.getEventType() == UpdatePresenter.update_fail) {
                ByAlert.alert("更新解析失败");
            }
        }
    }

    public String getAppVersionName(Context context) {
        String versionName = "";
        try {
            // ---get the package info---
            PackageManager pm = context.getPackageManager();
            PackageInfo pi = pm.getPackageInfo(context.getPackageName(), 0);
            versionName = pi.versionName;

            if (versionName == null || versionName.length() <= 0) {
                return "";
            }
        } catch (Exception e) {
            Log.e("VersionInfo", "Exception", e);
        }
        return versionName;
    }

    public void onManager(UpdateVersionBean appUpdateBean) {
        UpdateManager manager = new UpdateManager(this,
                appUpdateBean.getUpdate_log() + "",
                appUpdateBean.getDownload_url().get(0).getValue(), appUpdateBean.getVersion(),0);
        manager.checkUpdateInfo();
    }
}
